package com.gofaraway.common.util.bean;

import com.gofaraway.common.util.lambda.LambdaUtil;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author ChenPeng
 * @Date 2024/1/18 17:49
 */
public class PojoConvert {

    /**
     * 类型转换 非反射，速度更快 DO、DTO互转时使用
     *
     * @param source      来源实例  属性都有get方法
     * @param targetClass lambda 待转换类型
     * @param <T>
     * @return
     */
    public static <T> T copyProperties(Object source, Supplier<T> targetClass) {
        T target = targetClass.get();
        if (source == null) {
            return target;
        }
        BeanCopierUtil.copy(source, target);
        return target;
    }

    /**
     * 非反射，速度快
     *
     * @param sourceList  源集合对象
     * @param targetClass 目标对象
     * @param <T>
     * @param <U>
     * @return 属性复制后的集合对象
     */
    public static <T, U> List<T> beanListConvert(@NotNull List<U> sourceList, @NotNull Supplier<T> targetClass) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return Collections.emptyList();
        }
        return LambdaUtil.convertList(sourceList, source -> copyProperties(source, targetClass));
    }

    /**
     * beanListConvert
     *
     * @param sourceList
     * @param targetClass
     * @param consumer
     * @return java.util.List<T>
     * @Author: LiYuhang
     * @Date 2022/1/13 16:25
     */
    public static <T, U> List<T> beanListConvert(@NotNull List<U> sourceList,@NotNull Supplier<T> targetClass,@NotNull Consumer<T> consumer) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return Collections.emptyList();
        }
        return LambdaUtil.convertList(sourceList, source -> copyProperties(source, targetClass), consumer);
    }

    public static void main(String[] args) {
        List<Source> sourceList = new ArrayList<>();
        sourceList.add(new Source() {{
            setName("Alice");
            setAge(30);
        }});
        sourceList.add(new Source() {{
            setName("Bob");
            setAge(25);
        }});




        List<Target> targetList = copyProperties(
                Target::new,
                () -> sourceList,
                target -> {
                    target.setName(target.getName().toUpperCase());
                }
        );

        targetList.forEach(System.out::println);
    }


    static class Source {
        private String name;
        private int age;

        // Getters and setters
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }

    static class Target {
        private String name;
        private int age;

        // Getters and setters
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Target{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

    /**
     * @param sourceList  lambda 源集合对象
     * @param targetClass lambda 静态 构造 函数方法引用
     * @param <T>         源对象
     * @param <U>         目标对象
     * @return 属性复制后的集合对象
     */
    public static <T, U> List<T> copyProperties(@NotNull Supplier<List<U>> sourceList,@NotNull Supplier<T> targetClass) {
        return beanListConvert(sourceList.get(), targetClass);
    }

    /**
     * 属性copy
     *
     * @param sourceList
     * @param targetClass
     * @param consumer
     * @return java.util.List<T>
     * @Author: LiYuhang
     * @Date 2022/1/13 16:25
     */
    public static <T, U> List<T> copyProperties(@NotNull Supplier<T> targetClass,@NotNull Supplier<List<U>> sourceList,
                                                @NotNull Consumer<T> consumer) {
        return beanListConvert(sourceList.get(), targetClass, consumer);
    }

    /**
     * 类型转换
     *
     * @param source 要获取的对象
     * @param target 转换后返回的对象
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T, R> R getAndConvert(Supplier<T> source, Supplier<R> target) {
        T t = source.get();
        if (Objects.nonNull(t)) {
            return getAndConvert(t, target);
        }
        return target.get();
    }

    /**
     * 类型转换
     *
     * @param source
     * @param target
     * @param <R>
     * @return
     */
    public static <R> R getAndConvert(Object source, Supplier<R> target) {
        R r = target.get();
        if (Objects.isNull(source)) {
            return r;
        }
        BeanCopierUtil.copy(source, r);
        return r;
    }

    /**
     * 转换为 TreeMap<String, String>
     *
     * @param source 源对象  属性必须有get方法
     * @return
     */
    public static TreeMap<String, String> bean2TreeMap(Object source) {
        if (source == null) {
            return null;
        }
        TreeMap<String, String> map = new TreeMap<String, String>();
        bean2Map(source, map);
        return map;
    }

    /**
     * 转换为 HashMap<String, String>
     *
     * @param source 源对象  属性必须有get方法
     * @return
     */
    public static HashMap<String, String> bean2HashMap(Object source) {
        if (source == null) {
            return null;
        }
        HashMap<String, String> map = new HashMap<String, String>();
        bean2Map(source, map);
        return map;
    }

    private static void bean2Map(Object source, Map<String, String> map) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(source.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();

                // 过滤class属性
                if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(source);
                    if (null != value) {
                        map.put(key, String.valueOf(value));
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            //throw new UtilException("transBean2Map Error: " + e.getMessage());
        }
    }

    /**
     * 利用反射将map集合封装成bean对象
     *
     * @param map
     * @param clazz
     * @return
     */
    @Deprecated
    public static <T> T mapToBean(Map<String, ?> map, Class<T> clazz) {
        try {
            Object obj = clazz.newInstance();
            if (map != null && !map.isEmpty() && map.size() > 0) {
                for (Map.Entry<String, ?> entry : map.entrySet()) {
                    String propertyName = entry.getKey();    // 属性名
                    Object value = entry.getValue();        // 属性值
                    String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(
                            1);
                    Field field = getClassField(clazz, propertyName);    //获取和map的key匹配的属性名称
                    if (field == null) {
                        continue;
                    }
                    Class<?> fieldTypeClass = field.getType();
                    value = convertValType(value, fieldTypeClass);
                    try {
                        clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return (T)obj;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /********************************************************************************************************************/

    /**
     * 根据给定对象类匹配对象中的特定字段
     *
     * @param clazz
     * @param fieldName
     * @return
     */
    private static Field getClassField(Class<?> clazz, String fieldName) {
        if (Object.class.getName().equals(clazz.getName())) {
            return null;
        }
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }
        Class<?> superClass = clazz.getSuperclass();    //如果该类还有父类，将父类对象中的字段也取出
        if (superClass != null) {                        //递归获取
            return getClassField(superClass, fieldName);
        }
        return null;
    }

    /**
     * 将map的value值转为实体类中字段类型匹配的方法
     *
     * @param value
     * @param fieldTypeClass
     * @return
     */
    private static Object convertValType(Object value, Class<?> fieldTypeClass) {
        Object retVal = null;

        if (Long.class.getName().equals(fieldTypeClass.getName())
                || long.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Long.parseLong(value.toString());
        } else if (Integer.class.getName().equals(fieldTypeClass.getName())
                || int.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Integer.parseInt(value.toString());
        } else if (Float.class.getName().equals(fieldTypeClass.getName())
                || float.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Float.parseFloat(value.toString());
        } else if (Double.class.getName().equals(fieldTypeClass.getName())
                || double.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Double.parseDouble(value.toString());
        } else {
            retVal = value;
        }
        return retVal;
    }
}
